package com.rc.saas.tenant.mq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rc.saas.tenant.model.ticket.MemberTicket;
import com.rc.saas.tenant.model.ticket.MemberTicketExample;
import com.rc.saas.tenant.model.ticket.TenantTicketSendRecord;
import com.rc.saas.tenant.model.ticket.TenantTicketType;
import com.rc.saas.tenant.service.ticket.MemberTicketService;
import com.rc.saas.tenant.service.ticket.TenantTicketSendRecordService;
import com.rc.saas.tenant.service.ticket.TenantTicketTypeService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class TicketListener {
    private static Logger logger = LogManager.getLogger(PlatformApplyListener.class);

    @Autowired
    private TenantTicketTypeService ticketTypeService;

    @Autowired
    private TenantTicketSendRecordService ticketSendRecordService;

    @Autowired
    private MemberTicketService memberTicketService;


    @RabbitHandler
    @RabbitListener(queues = {"send_ticket"})
    public void sendTiketListener(Message message, Channel channel) throws Exception {
        String msg = new String(message.getBody(), "UTF-8");
        logger.info("sendTiketListener 收到了:{}", msg);


        HashMap<String, Object> map = JSON.parseObject(msg, HashMap.class);

        long ticketId = ((Integer) map.get("ticketId")).longValue();
        List<Long> memberIdList = new ArrayList<>();
        if (map.get("memberIdList") != null) {
            memberIdList =  ((List<Integer>)map.get("memberIdList")).stream().map(Integer::longValue).collect(Collectors.toList());
        }

        if (CollectionUtils.isEmpty(memberIdList)) {
            return;
        }


        TenantTicketType ticketType = ticketTypeService.selectByPrimaryKey(ticketId);
        int remain = ticketType.getRemainTicket();

        Date endTime = null;
        if ("1".equals(ticketType.getEffectType())) {
            endTime = ticketType.getEffectEndDate();
        } else if ("0".equals(ticketType.getEffectType())) {
            LocalDateTime localDateTime = LocalDateTime.now();
            LocalDateTime endDateTime = localDateTime.plusDays(ticketType.getEffectDay());
            endTime = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());
        }

        MemberTicketExample memberTicketExample = new MemberTicketExample();
        memberTicketExample.createCriteria().andMemberIdIn(memberIdList).andTicketTypeIdEqualTo(ticketId);
        Set<Long> memberIdSet = memberTicketService.selectByExample(memberTicketExample).stream().map(MemberTicket::getMemberId).collect(Collectors.toSet());


        for (Long memberId : memberIdList) {
            if (remain > 0) {
                if (memberIdSet.contains(memberId)) {
                    continue;
                }
                TenantTicketSendRecord ticketSendRecord = new TenantTicketSendRecord();
                ticketSendRecord.setTicketTypeId(ticketId);
                ticketSendRecord.setSendCount(1);
                ticketSendRecord.setSendTime(new Date());
                ticketSendRecord.setSendType("0");
                ticketSendRecordService.insertReturnId(ticketSendRecord);

                MemberTicket memberTicket = new MemberTicket();
                memberTicket.setMemberId(memberId);
                memberTicket.setTicketTypeId(ticketId);
                memberTicket.setTicketSendRecordId(ticketSendRecord.getTicketSendRecordId());
                memberTicket.setTicketSource("0");

                memberTicket.setEndTime(endTime);
                memberTicket.setGainTime(new Date());
                memberTicket.setStatus("0");
                memberTicket.setCreatedTime(new Date());
                memberTicketService.insertSelective(memberTicket);
                remain--;

            } else {
                break;
            }
        }

        ticketType.setRemainTicket(remain);
        ticketTypeService.updateByPrimaryKeySelective(ticketType);
        return;

    }
}
